//
//  HomeViewController.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/2.
//  Copyright © 2019 李文强. All rights reserved.
//

#import "HomeViewController.h"
#import "HPLeftTopView.h"
#import "HPClassView.h"
#import "HPOtherView.h"
#import "HPOtherRightView.h"
#import "HPFuDaoView.h"
#import "CalendarView.h"
#import "MainNavigationController.h"
#import "LoginViewController.h"
#import "CJClassSelectedView.h"
#import "HPSelectedClassView.h"
#import "SYRequestAPI+HomePage.h"
#import "HomePageLunBoTuModel.h"
#import "TeacherClassListModel.h"
#import "HomeCourseModel.h"
//师训信息
#import "HomeShiXunModel.h"
//在线辅导信息
#import "HomeOnlinTrainModel.h"
//最新作业
#import "TheNewWorkListModel.h"
//考勤异常
#import "SYKaoQinYiChangViewController.h"
#import "XGPush.h"


@interface HomeViewController ()<SDCycleScrollViewDelegate,HPClassSelectedDateDelegate,HPLeftTopDelegate,CalendarBlockDelegate,XGPushTokenManagerDelegate>
@property (nonatomic, retain) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) HPLeftTopView *leftTopView;
@property (nonatomic, strong) HPClassView *rightTopView;
@property (nonatomic, strong) HPOtherView *otherLeftView;
@property (nonatomic, strong) HPOtherRightView *otherRightView;
@property (nonatomic, strong) HPFuDaoView *fuDaoView;
//@property (nonatomic, strong) CalendarView *canderView;
@property (nonatomic, strong) HPSelectedClassView *hpClassView;
//轮播图数组
@property (nonatomic, strong) NSMutableArray *lunBoTuArray;
//教师课程列表
@property (nonatomic, strong) NSMutableArray *classListArray;
//即将开始的课程数组
@property (nonatomic, strong) NSMutableArray *beginCourseListArray;
//最新作业列表
@property (nonatomic, strong) NSMutableArray *homeWorkListArray;
//师训信息
@property (nonatomic, strong) NSMutableArray *trainListArray;
//在线辅导model
@property (nonatomic, strong) NSMutableArray *onlineTrainListArray;
//当前显示的教师班级作业的班级 model
@property (nonatomic, strong) TeacherClassListModel *currentMentorClassModel;
//选择最近课程的时间
@property (nonatomic, strong) NSString *dateString;
@end

@implementation HomeViewController
- (HPLeftTopView *)leftTopView{
    if (!_leftTopView) {
        HPLeftTopView *view = [[HPLeftTopView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        view.myDelegate  = self;
        _leftTopView = view;
    }
    return _leftTopView;
}
#pragma mark - 弹出选择班级
- (void)LeftClassClick{
    
//    SYKaoQinYiChangViewController *kqycVC = [[SYKaoQinYiChangViewController alloc] init];
//    kqycVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//    [self presentViewController:kqycVC animated:YES completion:nil];

    
    //先注释了。等测试过后解开
    _hpClassView = [[HPSelectedClassView alloc]init];
    _hpClassView.dataArray = _classListArray;
    _hpClassView.preferredContentSize = CGSizeMake(360, 300);
    _hpClassView.view.backgroundColor = [UIColor whiteColor];
    _hpClassView.popoverPresentationController.sourceView = self.view;
    _hpClassView.modalPresentationStyle = UIModalPresentationPopover;
    _hpClassView.popoverPresentationController.sourceView = self.view;
    _hpClassView.popoverPresentationController.sourceRect = CGRectMake(368*fw+80, 330, 0, 0);
    _hpClassView.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    [self presentViewController:_hpClassView animated:YES completion:nil];
//    __block HomeViewController *mySelf = self;
//    _hpClassView.block = ^(int index) {
//        //得到选择的当前班级
//        mySelf.currentMentorClassModel = [TeacherClassListModel new];
//        mySelf.currentMentorClassModel = mySelf.classListArray[index];
//        //得到作业数据
//        [mySelf zuiXinZuoYeRequest];
//    };
}
- (HPOtherView *)otherLeftView{
    if (!_otherLeftView) {
        HPOtherView *view = [[HPOtherView alloc]initWithFrame:CGRectMake(0, 0,fw*219,fh*119)];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        _otherLeftView = view;
    }
    return _otherLeftView;
}
- (HPOtherRightView *)otherRightView{
    if (!_otherRightView) {
        HPOtherRightView *view = [[HPOtherRightView alloc]initWithFrame:CGRectMake(0, 0,fw*219,fh*119)];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        _otherRightView = view;
    }
    return _otherRightView;
}

- (HPClassView *)rightTopView{
    if (!_rightTopView) {
        HPClassView *view = [[HPClassView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        view.delegate  =self;
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        _rightTopView = view;
    }
    return _rightTopView;
}
- (HPFuDaoView *)fuDaoView{
    if (!_fuDaoView) {
        HPFuDaoView *view = [[HPFuDaoView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        _fuDaoView = view;
    }
    return _fuDaoView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MAINBACKCOLOR;
    // Do any additional setup after loading the view.
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(0, 20, APP_WIDTH, 1);
    lineView.backgroundColor = LINCOLOR;
    [self.view addSubview:lineView];
    _lunBoTuArray = [NSMutableArray new];
    _classListArray = [NSMutableArray new];
    _beginCourseListArray = [NSMutableArray new];
    _homeWorkListArray = [NSMutableArray new];
    _trainListArray = [NSMutableArray new];
    _onlineTrainListArray = [NSMutableArray new];
    [self boundNoticeAcount];
//    if ([XGPush defaultManager].xgApplicationBadgeNumber > 0) {
        [[XGPush defaultManager] setXgApplicationBadgeNumber:0];
//    }
    [self getMentorClassListRequest];
}
- (void)boundNoticeAcount{
    NSString *count = [USERDEFAL objectForKey:AcountIDDefalut];
    //解绑账号：
    [[XGPushTokenManager defaultTokenManager] unbindWithIdentifer:count type:XGPushTokenBindTypeAccount];
    //绑定标签：
    [[XGPushTokenManager defaultTokenManager] bindWithIdentifier:count type:XGPushTokenBindTypeAccount];
    [[XGPushTokenManager defaultTokenManager] setDelegate:self];
}

- (void)xgPushDidBindWithIdentifier:(nonnull NSString *)identifier type:(XGPushTokenBindType)type error:(nullable NSError *)error {
    
}
- (void)viewWillAppear:(BOOL)animated{
    
}
- (void)initSubView{
    [self addScrollView];
    [self.view addSubview:self.leftTopView];
    [self.view addSubview:self.rightTopView];
    [self.view addSubview:self.otherLeftView];
    [self.view addSubview:self.otherRightView];
    //辅导
    [self.view addSubview:self.fuDaoView];
    
    _otherLeftView.goZuoYeBlock = ^(TheNewWorkListModel * _Nonnull model) {
        //NSLog(@"前往作业 %@",model.className);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"GoWorkListDetailNotification" object:nil userInfo:@{@"model":model}];
    };
    _otherRightView.goZuoYeBlock = ^(TheNewWorkListModel * _Nonnull model) {
       // NSLog(@"前往作业 %@",model.className);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"GoWorkListDetailNotification" object:nil userInfo:@{@"model":model}];
    };
}
#pragma mark - 前往作业
#pragma mark - 选择时间
- (void)selectedDate:(NSString *)date{
    [CalendarView initWithDateWithFrame:CGRectMake(self.view.frame.size.width-50, 330, 0, 0) andeSourceView:self.view andDelegate:self andSuccessBlock:^(NSString * _Nonnull date) {
       // NSLog(@"选择的时间 %@",date);
        self->_dateString = date;
        [self theForthcomingCourse];
    }];
}
- (void)getCalenderDate:(NSString *)date{
    
}
- (void)initOption{
   //获得老师班级
    [self getMentorClassListRequest];
    //最新作业
    [self zuiXinZuoYeRequest];
    //课程
    [self theForthcomingCourse];
    //辅导信息
    [self getFuDaoXinXIRequest];
    //师训信息
//    [self getTrainInforRequest];
}
- (void)layout{
    [_leftTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.width.equalTo(@0).offset(fw*452);
        make.top.equalTo(@284);
        make.height.equalTo(@0).offset(fh*296);
    }];
    [_rightTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@0).offset(-15);
        make.width.equalTo(@0).offset(fw*452);
        make.top.equalTo(@284);
        make.height.equalTo(@0).offset(fh*176);
    }];
    [_otherLeftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0).offset(15);
        make.width.equalTo(@0).offset(fw*219);
        make.top.equalTo(self.leftTopView.mas_bottom).offset(15);
        make.height.equalTo(@0).offset(fh*119);
    }];
    [_otherRightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.leftTopView.mas_right);
        make.width.equalTo(@0).offset(fw*219);
        make.top.equalTo(self.leftTopView.mas_bottom).offset(15);
        make.height.equalTo(@0).offset(fh*119);
    }];
    [_fuDaoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.rightTopView.mas_right);
        make.left.equalTo(self.rightTopView.mas_left);
        make.top.equalTo(self.rightTopView.mas_bottom).offset(15);
        make.height.equalTo(@0).offset(fh*239);
    }];
}
- (void)addScrollView{
    [self getLunBoTuData];
   
//    dispatch_async(dispatch_queue_create(0, 0), ^{
//        // 子线程执行任务（比如获取较大数据）
//        LoginViewController *loginView = [[LoginViewController alloc]init];
//        loginView.view.backgroundColor = [UIColor whiteColor];
//        loginView.modalPresentationStyle = UIModalPresentationOverFullScreen;
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // 通知主线程刷新 神马的
//            loginView.view.frame = se lf.view.frame;
//            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:loginView animated:YES completion:nil];
//
//        });
//    });

}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    
    
    
}

/** 图片滚动回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    
}
#pragma mark - 获取轮播图
- (void)getLunBoTuData{
    NSDictionary *parama = @{@"position":@"1"};
    [SYRequestAPI sy_getAdvertService:parama success:^(id  _Nonnull responseObject) {
        NSLog(@"得到首页轮播图 %@",responseObject);
        NSArray *dataArray = [responseObject objectForKey:@"data"];
        NSMutableArray *imageUrlArray = [NSMutableArray new];
        for (NSDictionary *dic in dataArray) {
            HomePageLunBoTuModel *model = [HomePageLunBoTuModel yy_modelWithJSON:dic];
            [self->_lunBoTuArray addObject:model];
            [imageUrlArray addObject:model.url];
        }
        if (self->_lunBoTuArray.count>0) {
            self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120) imageURLStringsGroup:imageUrlArray]; // 模拟网络延时情景
        }else{
            self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120) imageURLStringsGroup:@[@"u96",@"u100",@"u102"]]; // 模拟网络延时情景 
        }
        self.cycleScrollView.autoScrollTimeInterval = 3.0;
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
        // 一个Category给用颜色做ImageView 用15宽2高做一个长方形图片 当前图片
        self.cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"circle_home"];
        
        // 同上做一个 其他图片
        self.cycleScrollView.pageDotImage =  [UIImage imageNamed:@"circle_white"];
        self.cycleScrollView.delegate = self;
        [self.view addSubview:self.cycleScrollView];
        [self->_cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@15);
            make.right.equalTo(@0).offset(-15);
            make.top.equalTo(@20);
            make.height.equalTo(@254);
        }];
        
    } fail:^(NSError *error) {
    }];
}
#pragma mark - 最新作业
- (void)zuiXinZuoYeRequest{
    if (!_currentMentorClassModel) {
        _currentMentorClassModel = [TeacherClassListModel new];
        _currentMentorClassModel.id = @"0";
    }
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{@"classId":_currentMentorClassModel.id
                             };
    [SYRequestAPI sy_getHomeWork:parama success:^(id  _Nonnull responseObject) {
      //  NSLog(@"最新罪业信息 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        [self->_homeWorkListArray removeAllObjects];
        for (NSDictionary *dic in array) {
            TheNewWorkListModel *model = [TheNewWorkListModel yy_modelWithJSON:dic];
            [self->_homeWorkListArray addObject:model];
        }
        if (self->_homeWorkListArray.count > 2) {
            self->_otherLeftView.dataArray = self->_homeWorkListArray;
            [self->_otherLeftView updateView];
            
            self->_otherRightView.dataArray = self->_homeWorkListArray;
            [self->_otherRightView updateView];
            
        } else {
            self->_otherRightView.dataArray = self->_homeWorkListArray;
            [self->_otherRightView updateView];
        }
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
}
#pragma mark - 获得老师班级
- (void)getMentorClassListRequest{
    NSDictionary *parama = @{@"name":@"",
                             @"pageIndex":@"0",
                             @"pageSize":@"1000"};
    [SYRequestAPI sy_getClassList:parama success:^(id  _Nonnull responseObject) {
//        NSLog(@"得到老师班级 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            TeacherClassListModel *model = [TeacherClassListModel yy_modelWithJSON:dic];
            [self->_classListArray addObject:model];
        }
 /*
  持久化存储教师班级
  */
        [PublickFunctionObject saveArrayForData:[NSMutableArray arrayWithArray:array] forKey:ClassListOfTeacherDefalut];
    } fail:^(NSError *error) {
        
    }];
}
#pragma mark - 获得即将开始课程
- (void)theForthcomingCourse{
    if (_dateString.length == 0) {
        _dateString = @"";
    }
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{@"currentDate":_dateString};
    [SYRequestAPI sy_getTheForthcomingCourse:parama success:^(id  _Nonnull responseObject) {
        [self->_beginCourseListArray removeAllObjects];
       // NSLog(@"输出获得即将开始课程 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            HomeCourseModel *model = [HomeCourseModel yy_modelWithJSON:dic];
            [self->_beginCourseListArray addObject:model];
        }
        self->_rightTopView.dataArray = self->_beginCourseListArray;
        [self->_rightTopView updateView];
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
}
#pragma mark - 辅导信息
- (void)getFuDaoXinXIRequest{
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{@"classId":@"0"};
    [SYRequestAPI sy_getQuestionTutor:parama success:^(id  _Nonnull responseObject) {
        NSLog(@"得到辅导信息 %@",responseObject);
        [MBProgressHUD mj_hideHUDForView:self.view];
        NSArray *data = responseObject[@"data"];
        NSDictionary *dict = data.lastObject;
        NSArray *dataStudents = dict[@"dataStudents"];
        self.fuDaoView.dataArray = dataStudents;
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"回答问题：%@%@  共计：%@人 %@个问题",dict[@"answerDate"],dict[@"answerWeek"],dict[@"students"],dict[@"questions"]] attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: 12],NSForegroundColorAttributeName: [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]}];
        self.fuDaoView.timeLabel.attributedText = string;
        [self.fuDaoView updateView];
        
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
}
#pragma mark - 得到师训信息
//- (void)getTrainInforRequest{
//    [MBProgressHUD mj_showMessage:nil toView:self.view];
//    NSDictionary *parama = @{};
//    [SYRequestAPI sy_getTrain:parama success:^(id  _Nonnull responseObject) {
//        NSLog(@"得到师训信息 %@",responseObject);
//        NSArray *array = [responseObject objectForKey:@"data"];
//        for (NSDictionary *dic in array) {
//            HomeShiXunModel *model = [HomeShiXunModel yy_modelWithJSON:dic];
//            [self->_trainListArray addObject:model];
//        }
////        self->_otherLeftView.dataArray = self->_trainListArray;
////        [self->_otherLeftView updateView];
//        [MBProgressHUD mj_hideHUDForView:self.view];
//    } fail:^(NSError *error) {
//        [MBProgressHUD mj_hideHUDForView:self.view];
//    }];
//}
#pragma mark - sy_getOnLineTutor在线辅导信息
- (void)getZaiXianFuDaoRequest{
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{};
    [SYRequestAPI sy_getOnLineTutor:parama success:^(id  _Nonnull responseObject) {
     //   NSLog(@"得到师训信息 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            HomeOnlinTrainModel *model = [HomeOnlinTrainModel yy_modelWithJSON:dic];
            [self->_onlineTrainListArray addObject:model];
        }
        self->_fuDaoView.dataArray = self->_trainListArray;
        [self->_fuDaoView updateView];
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"GoWorkListDetailNotification" object:nil];
}
@end
